"""Copyright (c) 2010, Helsinki Institute of Information Technology HIIT
Matti Nelimarkka <matti.nelimarkka@hiit.fi>

All rights reserved.

Redistribution and use in source and binary forms,
with or without modification, are permitted provided that 
the following conditions are met:

Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

Neither the name of the Helsinki Institute of Information Technology HIIT 
nor the names of  its contributors may be used to endorse or promote products derived 
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import inbox,  appuifw, e32
import socket, urllib

URL = "http://labs.humanisti.fixme.fi/sizzle/ossi/jsclient/v1_tester/alllog.php?"

def message_received( id ):
    box = inbox.Inbox()
    try:
        sms_text = box.content( id )
        sms_text = urllib.quote( sms_text.encode('utf8') )
        sms_number = box.address( id )
        data = {"sms" : sms_text, "number" : sms_number}
        data = urllib.urlencode( data )
        urllib.urlopen(URL + data)
        global count
        count = count + 1
        print "Message " + str( count )
    except SymbianError:
        print 'Symbian failure'
        message_received( id )
    

def init_handler():
    box = inbox.Inbox()
    box.bind( message_received )
    app_lock.wait()

## Setup
## TODO: ugly >.<
aps = [ap['name'] for ap in socket.access_points()]
aps.sort()
apid = appuifw.popup_menu(aps,u'Select gateway')
socket.set_default_access_point(aps[apid])

## Init
app_lock = e32.Ao_lock()
count = 0
print "Initializing gateway"
init_handler()
print "Gateway closed"